<?php

/**
 * Little PHP Proxy for communicating with BOSH Service via Port 80
 * Forwards all client requests to BOSH Service on Port 5280 and outputs the result to client
 * (Client is for example a strophe.js library)
 *
 * @author Jan Stuhlmann
 */

define(BOSH_SERVICE_URL, 'URL-TO-YOUR-BOSH-SERVICE');
define(BOSH_SERVICE_PORT, 5280);
define('NL', "\r\n");

$fp=fopen('php://input', 'r');
$rawpost = stream_get_contents($fp);
fclose($fp);

$socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//socket_set_nonblock($socket);
$address = gethostbyname(BOSH_SERVICE_URL);


if (socket_connect($socket, $address, BOSH_SERVICE_PORT)) {
  $post=Array();

  $post[]='POST /http-bind HTTP/1.1';
  $post[]='Host: '.$_SERVER['REMOTE_HOST'];
  $post[]='User-Agent: HE Bosh Proxy';
  $post[]='Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
  $post[]='Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3';
  $post[]='Keep-Alive: 115';
  $post[]='Connection: keep-alive';
  $post[]='Content-Length: '.strlen($rawpost);
  $post[]='Content-Type: text/plain; charset=UTF-8';
  $post[]='';
  $post[]=$rawpost;
  $post[]='';


  socket_write($socket, implode(NL, $post));

  socket_set_nonblock($socket);
  $timeout=time() + 2;
  $recvd='';
  $contentLength=null;
  $content=null;

  do {
    $ret=socket_read($socket, 4096);
    $recvd.=$ret;

    $lines=explode(NL, $recvd);
    foreach ($lines as $line) {
      if (strpos($line, 'Content-Length:') === 0) {
        $expl=explode('Content-Length:', $line);
        $contentLength=(int)trim($expl[1]);
      }
    }
    if ($contentLength) {
      $expl=explode(NL.NL, $recvd);
      $content=$expl[1];

      if (strlen($content) >= $contentLength) {
        break;
      }
    }
  } while (time() < $timeout);
  echo $content;
} else {
  echo 'Socket Connect Error: '.socket_strerror(socket_last_error($socket));
}
socket_close($socket);

/*
$lines=file('http://memcache.www.intern.hosteurope.de/http-bind:5280');
foreach ($lines as $line) {
  echo $line;
}
*/